﻿using System;
using System.Data;
using TestCenter.DataSet;
using TestCenter.DataSet.UserDataSetTableAdapters;
using TestCenter.DataSet.QuestionDataSetTableAdapters;
using TestCenter.DataSet.CheckActionDataSetTableAdapters;

namespace TestCenter.Classes
{
    class Connection
    {
        public static bool IsValidAccount(string username, string password,
            ref User user)
        {
            var userTableAdapter = new UserTableAdapter();
            var userTable = new UserDataSet.UserDataTable();
            userTableAdapter.Fill(userTable);

            var result = userTable.Select("Username = '" + username + "' and Password = '" + password + "'");
            if (result.Length > 0)
            {
                SetUserInfo(result[0], ref user);
                return true;
            }

            user = null;
            return false;
        }

        private static void SetUserInfo(DataRow dataRow, ref User user)
        {
            if (user != null)
            {
                user.Username = dataRow["Username"].ToString();
                user.FullName = dataRow["Fullname"].ToString();
                user.Sex = dataRow["Sex"].ToString();
                user.Email = dataRow["Email"].ToString();
                user.DateOfBirth = (DateTime) dataRow["DOB"];
            }
        }

        public static DataRowCollection GetAllQuestion()
        {
            var adapter = new QuestionTableAdapter();
            var table = new QuestionDataSet.QuestionDataTable();
            adapter.Fill(table);
            return table.Rows;
        }

        public static DataRow[] GetAllAnswer(string questionId)
        {
            var adapter = new CheckActionTableAdapter();
            var table = new CheckActionDataSet.CheckActionDataTable();
            adapter.Fill(table);
            table.OrderBy(row => row.ActionIndex);
            return table.Select("QuestionId = '" + questionId + "'");
        }
    }
}
